import React, { createContext, useContext, useState, ReactNode } from 'react';

export interface Friend {
  id: string;
  username: string;
  avatar: string;
  status: 'online' | 'offline';
  lastSeen?: string;
}

interface FriendContextType {
  friends: Friend[];
  loading: boolean;
  addFriend: (friendId: string) => Promise<void>;
  removeFriend: (friendId: string) => Promise<void>;
  getFriendProfile: (friendId: string) => Friend | undefined;
}

const FriendContext = createContext<FriendContextType | null>(null);

export const useFriend = () => {
  const context = useContext(FriendContext);
  if (!context) {
    throw new Error('useFriend must be used within a FriendProvider');
  }
  return context;
};

interface FriendProviderProps {
  children: ReactNode;
}

export const FriendProvider: React.FC<FriendProviderProps> = ({ children }) => {
  const [friends, setFriends] = useState<Friend[]>([
    {
      id: '1',
      username: '张三',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Felix',
      status: 'online',
      lastSeen: new Date().toISOString()
    },
    {
      id: '2',
      username: '李四',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Lily',
      status: 'offline',
      lastSeen: '2024-01-20T10:30:00Z'
    },
    {
      id: '3',
      username: '王五',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Mike',
      status: 'online',
      lastSeen: new Date().toISOString()
    }
  ]);
  const [loading, setLoading] = useState(false);

  const addFriend = async (friendId: string) => {
    try {
      setLoading(true);
      // 这里应该调用后端API添加好友
      const response = await fetch(`/api/friends/add/${friendId}`, {
        method: 'POST',
      });

      if (!response.ok) {
        throw new Error('添加好友失败');
      }

      const newFriend = await response.json();
      setFriends(prev => [...prev, newFriend]);
    } catch (error) {
      console.error('添加好友错误:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const removeFriend = async (friendId: string) => {
    try {
      setLoading(true);
      // 这里应该调用后端API删除好友
      const response = await fetch(`/api/friends/remove/${friendId}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        throw new Error('删除好友失败');
      }

      setFriends(prev => prev.filter(friend => friend.id !== friendId));
    } catch (error) {
      console.error('删除好友错误:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const getFriendProfile = (friendId: string) => {
    return friends.find(friend => friend.id === friendId);
  };

  return (
    <FriendContext.Provider
      value={{
        friends,
        loading,
        addFriend,
        removeFriend,
        getFriendProfile,
      }}
    >
      {children}
    </FriendContext.Provider>
  );
};